package com.moefor.clover.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.moefor.clover.model.*;
import com.moefor.clover.model.element.Picture;
import com.moefor.clover.model.enums.CloverSessionKey;
import com.moefor.clover.service.CommunicationService;
import com.moefor.clover.service.ShopService;
import com.moefor.clover.service.UserService;
import com.moefor.clover.util.Encrypt;
import com.moefor.clover.util.MessagePackager;

@Controller
public class ShopController {
	@Resource
	private ShopService shopService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private CommunicationService communicationService;
	
	@ResponseBody
	@RequestMapping(value = "/common/test.do")
	public MessagePackager test(){
		MessagePackager msgPack = new MessagePackager();
		msgPack.setCode("");
		msgPack.setState(true);
		User u = (User)userService.val("adminer", "1e5334caed399aed8b9abba51ee8bb94").getData();
		//Integer a = u.getGoodsItems().size();
		Hibernate.initialize(u.getGoodsItems());
		for(Goods g : u.getGoodsItems()){
			Hibernate.initialize(g.getPicItems());
			g.setOwner(null);
		}
		msgPack.setData(u);
		
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/goods/get.do")
	public MessagePackager getGoods(@RequestParam("goods_id") Integer goodsId){
		MessagePackager msgPack;
		if(goodsId == null){
			msgPack = new MessagePackager(false, null, "商品ID错误!");
		}else msgPack = shopService.getGoods(goodsId);
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/goods/search.do")
	public MessagePackager searchGoods(
			@RequestParam("keyword") String keyword,
			@RequestParam("page_num") Integer pageNum,
			@RequestParam("page_size") Integer pageSize,
			@RequestParam("pointX") Double pointX,
			@RequestParam("pointY") Double pointY){
		MessagePackager msgPack = null;
		
		if(pageNum == null || pageSize == null || pointX == null || pointY == null){
			msgPack = new MessagePackager(false, null, "非法请求");
			return msgPack;
		}
		if(keyword == null) keyword = "";
		
		msgPack = shopService.getAroundMarket(pointX, pointY);
		if(!msgPack.getState()) return msgPack;
		Set<Market> marketSet = (Set<Market>)msgPack.getData();
		msgPack = shopService.searchGoods(keyword, pageNum, pageSize, marketSet);
		if(msgPack.getState()){
			Set<Goods> goodsSet = (Set<Goods>)msgPack.getData();
			for(Goods g : goodsSet){
				//Hibernate.initialize(g.getCommentItems());
				for(Comment c : g.getCommentItems()){
					c.setGoods(null);
				}
			}
			msgPack.setData(goodsSet);
		}
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/goods/search_by_market.do")
	public MessagePackager searchGoodsByMarket(
			@RequestParam("keyword") String keyword,
			@RequestParam("page_num") Integer pageNum,
			@RequestParam("page_size") Integer pageSize){
		MessagePackager msgPack = null;
		
		if(pageNum == null || pageSize == null){
			msgPack = new MessagePackager(false, null, "非法请求");
			return msgPack;
		}
		if(keyword == null) keyword = "";
		
		msgPack = shopService.searchGoodsByMakret(keyword, pageNum, pageSize);
		if(msgPack.getState()){
			Set<Goods> goodsSet = (Set<Goods>)msgPack.getData();
			for(Goods g : goodsSet){
				for(Comment c : g.getCommentItems()){
					c.setGoods(null);
				}
			}
			msgPack.setData(goodsSet);
		}
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/goods/search_by_market_id.do")
	public MessagePackager searchGoodsByMarket(
			@RequestParam("market_id") Integer keyword,
			@RequestParam("page_num") Integer pageNum,
			@RequestParam("page_size") Integer pageSize){
		MessagePackager msgPack = null;
		
		if(pageNum == null || pageSize == null || keyword == null){
			msgPack = new MessagePackager(false, null, "非法请求");
			return msgPack;
		}
		
		msgPack = shopService.searchGoodsByMakret(keyword, pageNum, pageSize);
		if(msgPack.getState()){
			Set<Goods> goodsSet = (Set<Goods>)msgPack.getData();
			for(Goods g : goodsSet){
				for(Comment c : g.getCommentItems()){
					c.setGoods(null);
				}
			}
			msgPack.setData(goodsSet);
		}
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/market/search_around.do")
	public MessagePackager searchAroundMarket(
			@RequestParam("pointX") Double pointX,
			@RequestParam("pointY") Double pointY){
		MessagePackager msgPack = null;
		if(pointX == null || pointY == null){
			msgPack = new MessagePackager(false, null, "非法请求");
			return msgPack;
		}
		msgPack = shopService.getAroundMarket(pointX, pointY);
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/market/get.do")
	public MessagePackager getMarket(@RequestParam("market_id") Integer marketId){
		MessagePackager msgPack = null;
		if(marketId == null){
			msgPack = new MessagePackager(false, null, "非法请求");
		}else{
			msgPack = shopService.getMarket(marketId);
		}
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/market/search.do")
	public MessagePackager searchMarket(@RequestParam("keyword") String keyword){
		MessagePackager msgPack = null;
		if(keyword == null){
			keyword = "";
		}
		msgPack = shopService.searchMarket(keyword);
		
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/common/market/get_around.do")
	public MessagePackager getAroundMarket(@RequestParam("pointX") Double pointX, @RequestParam("pointY") Double pointY){
		MessagePackager msgPack;
		if(pointX == null || pointY == null){
			msgPack = new MessagePackager(false, "DATA_FORMAT_ERROR", "数据格式错误!");
			return msgPack;
		}
		msgPack = shopService.getAroundMarket(pointX, pointY);
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/goods/book.do")
	public MessagePackager bookGoods(HttpSession session,
			@RequestParam("goods_id") Integer goodsId,
			@RequestParam("remarks") String remarks){
		MessagePackager msgPack = null;
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = shopService.bookGoods(user, goodsId, remarks);
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/goods/ban.do")
	public MessagePackager banGoods(HttpSession session, @RequestParam("goods_id") Integer goodsId){
		MessagePackager msgPack = null;
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = shopService.banGoods(user, goodsId);
		return msgPack;
	}
	
	@ResponseBody
	@RequestMapping(value = "/goods/add.do")
	public MessagePackager addGoods(
			HttpSession session,
			HttpServletResponse response,
			@RequestParam("name") String goodsName,
			@RequestParam("price") Float goodsPrice,
			@RequestParam("des") String goodsIntroduction,
			@RequestParam("market") String[] marketListId,
			@RequestParam(value = "file", required=false) MultipartFile[] files){
		MessagePackager msgPack = new MessagePackager(false, null, "未知错误!");
		if(goodsName == null || goodsPrice == null || goodsIntroduction == null || marketListId == null || goodsName.equals("") || goodsIntroduction.equals("") || marketListId.equals("")){
			msgPack.setData("数据不能为空!");
			return msgPack;
		}
		
		if(files == null || files.length < 1){
			msgPack.setData("商品图片不能为空!");
			return msgPack;
		}
		Set<Market> marketItems= new HashSet<Market>();
		for(String id : marketListId){
			Market m = new Market();
			if(id == null || id.equals("")) continue;
			msgPack = shopService.getMarket(Integer.valueOf(id));
			if(!msgPack.getState()) return msgPack;
			marketItems.add((Market)msgPack.getData());
		}
		
		if(marketItems.isEmpty()){
			msgPack.setState(false);
			msgPack.setData("市场不能为空!");
			return msgPack;
		}
		
		Set<Picture> picItems = new HashSet<Picture>();
		for(int i=0; i<files.length; i++){

			MultipartFile file = files[i];
			try {
				if (!file.isEmpty()) { 
					String url = "data/img/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + 
												(int) ((new Random().nextDouble() * (99999 - 10000 + 1)) + 10000) + 
												Encrypt.MD5(file.getOriginalFilename()) + ".jpg";
					String filePath = session.getServletContext().getRealPath("/") + url; 
	                file.transferTo(new File(filePath));
	                Picture pic = new Picture();
	                pic.setUrl(url);
	                picItems.add(pic);
				}
			} catch (Exception e) {
				// TODO: handle exception
				msgPack.setData("上传图片失败!");
				return msgPack;
			}
		}
		if(picItems.size() < 1){
			msgPack.setState(false);
			msgPack.setData("商品图片不能为空!");
			return msgPack;
		}
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = shopService.addGoods(user, goodsName, goodsIntroduction, goodsPrice, marketItems, picItems);
		return msgPack;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/comment/send.do")
	public MessagePackager sendComment(
			HttpSession session,
			@RequestParam("goods_id") Integer goodsId,
			@RequestParam("content") String content,
			@RequestParam(value = "reply_user_id", required = false) Integer replyUserId){
		MessagePackager msgPack = new MessagePackager(false, null, "未知错误!");
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = communicationService.sendComment(user, goodsId, content, replyUserId);
		return msgPack;
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/order/finish.do")
	public MessagePackager cfmdOrder(HttpSession session, @RequestParam("goods_id") Integer goodsId){
		MessagePackager msgPack = null;
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = shopService.finishedOrder(user, goodsId);
		return msgPack;
	}
	/*
	@ResponseBody
	@RequestMapping(value = "/order/reject.do")
	public MessagePackager rejectOrder(HttpSession session, @RequestParam("order_id") Integer orderId){
		MessagePackager msgPack = null;
		User user = (User)session.getAttribute(CloverSessionKey.USER);
		msgPack = shopService.cfmdOrder(user, orderId);
		return msgPack;
	}*/
}